
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

<html>
<head>
	<title>Device Orientation By PuterJam</title>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
</head>

<body>
<h1><ruby>设备方向感应测试<rt style="text-align:right;color:#ccc;font-size:10px">By PuterJam</rt></ruby></h1>
<div style="background:#000;width:400px;height:200px;color:#fff;border-radius:5px;">
	<div id="pointer" style="height:5px;width:5px;background:#fff;position:relative;border-radius:10px;-webkit-transition:all 0.1s ease-in;-moz-transition:all 0.1s ease-in">
	</div>
</div>
<div id="test" style="font-size:12px;-webkit-text-size-adjust:none;margin:6px;"></div>

<script defer>
	function Orientation(selector) {
	}

	Orientation.prototype.init = function(){

		window.addEventListener('deviceorientation', this.orientationListener, false);

		window.addEventListener('MozOrientation', this.orientationListener, false);

		window.addEventListener('devicemotion', this.orientationListener, false);

	}

	Orientation.prototype.orientationListener = function(evt) {
		// For FF3.6+
		if (!evt.gamma && !evt.beta) {
			// angle=radian*180.0/PI 在firefox中x和y是弧度值,

			evt.gamma = (evt.x * (180 / Math.PI)); //转换成角度值,
			evt.beta = (evt.y * (180 / Math.PI)); //转换成角度值
			evt.alpha = (evt.z * (180 / Math.PI)); //转换成角度值
		}

		/* beta:  -180..180 (rotation around x axis) */

		/* gamma:  -90..90  (rotation around y axis) */

		/* alpha:    0..360 (rotation around z axis) (-180..180) */

		var gamma = evt.gamma

		var beta = evt.beta

		var alpha = evt.alpha

		if(evt.accelerationIncludingGravity){
			// window.removeEventListener('deviceorientation', this.orientationListener, false);

			gamma = event.accelerationIncludingGravity.x*10

			beta = -event.accelerationIncludingGravity.y*10

			alpha = event.accelerationIncludingGravity.z*10
		}

		if (this._lastGamma != gamma || this._lastBeta != beta) {

			document.querySelector("#test").innerHTML = "x: "+ beta.toFixed(2) + " y: " + gamma.toFixed(2) + " z: " + (alpha != null?alpha.toFixed(2):0)

			var style = document.querySelector("#pointer").style;

			style.left = gamma/90 * 200 + 200 +"px";

			style.top = beta/90 * 100 + 100 +"px";

			this._lastGamma = gamma;

			this._lastBeta = beta;
		}
	};

	(new Orientation()).init();

</script>
</body>
</html>